﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Collections.Generic;
using BLL;
using WeChat.Common;
using Newtonsoft.Json.Linq;
using WeChat.Common2;
using WeChat.JsSDK.lib;
using Com.Alipay;
using Com.Alipay.Domain;
using Com.Alipay.Model;
using Com.Alipay.Business;
using System.Threading;
using WeChat.HyfPay.Hyflib;
using WeChat.HyfPay;
using Models;

namespace WeChat
{
    /// <summary>
    /// MsgService 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://wechat.jocat.com")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消对下行的注释。
    // [System.Web.Script.Services.ScriptService]
    public class MsgService : System.Web.Services.WebService
    {
        GetUserInfoBLL gb = new GetUserInfoBLL();

        [WebMethod(Description = "发送消息给指定用户id")]
        public string SendMsgtoUser(string UserID, string Msg)
        {
            string openid = gb.getOpenid(UserID);
            if (openid != "")
            {
                JObject jo = JObject.Parse(KefuSendMsg.sendText(openid, Msg));
                if (jo["errcode"].ToString() == "0")
                {
                    return "发送成功";
                }
                else
                {
                    return "发送失败，errcode:" + jo["errcode"].ToString();
                }
            }
            else
            {
                return "发送失败，请输入正确信息";
            }
        }

        [WebMethod(Description = "发送充值成功模板消息给指定用户id，time:时间;addMoney:充值金额;amount:账户余额")]
        public string SendTemplateMsg(string userID, string time, string addMoney, string amount)
        {
            string openid = gb.getOpenid(userID);
            if (openid != "")
            {
                string m = TemplateAction.sendTemplateMsg(openid, "4uzj7s80qQmsSDOhhkcWVhSqRn9fPxJIRtVrlxsIPEk", time, addMoney, amount);
                if (m == "0")
                {
                    return "发送成功";
                }
                else
                {
                    return "发送失败，errcod:" + m;
                }
            }
            else
            {
                return "发送失败，请输入正确用户id";
            }
        }

        [WebMethod(Description = "微信扫码支付获取二维码参数。cardID:用户参数(卡号); money:充值金额(元); order_No:订单编号")]
        public string getCode_url(string cardID, string money, string order_No)
        {
            string code_url = "";
            int moneys = (Int32)(Double.Parse(money) * 100);
            try
            {  
                code_url = WxPayApi.getJsApi("", moneys, cardID, order_No,"", "NATIVE");
            }
            catch (Exception ex)
            {
                ApplicationLog.Write("调用扫码支付失败：" + ex.Message);
            }
            return code_url;
        }
   
    [WebMethod(Description = "微信刷卡支付。cardID:用户参数(卡号); money:支付金额(元); attach:商品名称;order_No:订单编号;auth_code:授权码;")]
        public string getResult(string cardID, string money,string attach, string order_No,string auth_code)
        {
            int moneys = (Int32)(Double.Parse(money) * 100);
           // Thread thread = new Thread(new ThreadStart(WxPayApi.SlotCardApi));
            Thread thread = new Thread(new ParameterizedThreadStart(WxPayApi.SlotCardApi));
            object o = new Sparameter() { cardID = cardID, money = moneys.ToString(), attach= attach, order_No= order_No, auth_code= auth_code };
            thread.Start(o);
            return "1";
            //string result = "";
            //int moneys = (Int32)(Double.Parse(money) * 100);
            //try
            //{
            //    result=WxPayApi.SlotCardApi("", moneys, attach, order_No, auth_code);

            //}
            //catch (Exception ex)
            //{
            //    ApplicationLog.Write("调用刷卡支付失败：" + ex.Message);
            //}
            //// return "";
            //if (result == "" || result == null)
            //{
            //    return "FAIL";
            //}
            //else
            //{
            //    return result;
            //}
        }
        [WebMethod(Description = "查询订单。order_No:订单号")]
        public string getSelects(string order_No)
        {
            string result = "";
           // int moneys = (Int32)(Double.Parse(money) * 100);
            try
            {
                result = WxPayApi.getSelect(order_No);
            }
            catch (Exception ex)
            {
                ApplicationLog.Write("调用查询失败：" + ex.Message);
            }
            if (result == "" || result == null)
            {
                return "FAIL";
            }
            else
            {
                return result;
            }
        }
        [WebMethod(Description = "汇耘富扫码支付获取二维码参数。Type:支付类型(输入011为微信支付，输入009为支付宝支付);cardID:用户参数(卡号); goodsName:商品名称;amount:充值金额(元); order_No:订单编号")]
        public string getURL(string Type,string cardID,string goodsName, string amount, string order_No)
        {
            //  int amounts = (Int32)(Double.Parse(amount) * 100);
            string qrURL = "";
            try
            {
              qrURL = HyfPayApi.getResult(Type, order_No, goodsName, amount.ToString(), cardID,"");
            }
            catch (Exception ex)
            {
                ApplicationLog.Write("调用扫码支付失败：" + ex.Message);
            }
            return qrURL;
        }
       
        [WebMethod(Description = "汇耘富反扫支付。Type:支付类型(输入012为微信支付，输入010为支付宝支付);cardID:用户参数(卡号); goodsName:商品名称;amount:充值金额(元); order_No:订单编号;authCode:授权码")]
        public string getReverse(string Type, string cardID, string goodsName, string amount, string order_No,string authCode)
        {
            Thread thread = new Thread(new ParameterizedThreadStart(HyfPayApi.ReverseApi));
             object o = new HyfParameter() { Type= Type, cardID = cardID, amount = amount.ToString(), goodsName = goodsName, order_No = order_No, authCode = authCode };
               thread.Start(o);
            return "1";
            //string result = "";
            //try
            //{
            //    result = HyfPayApi.ReverseApi(Type, order_No, goodsName, amount.ToString(), cardID,authCode);
            //}
            //catch (Exception ex)
            //{
            //    ApplicationLog.Write("调用扫码支付失败：" + ex.Message);
            //}
            //return result;
        }
        [WebMethod(Description = "汇耘富二码合一扫码支付获取二维码参数。equipmentID:设备号;cardID:用户参数(卡号); amount:充值金额(元); order_No:订单编号")]
        public string getqrURL(string equipmentID,string goodsName, string order_No)
        {
          
            string qrURL ="http://" + Config.domainName + "/WeChat/JsSDK/WxPay/SyntheticPay.aspx?goodsName=" + goodsName +"&order_No=" + order_No+ "&equipmentID="+ equipmentID;
            return qrURL;
        }
        //AlipayHelperService serviceClient = AlipayF2FBiz.CreateClientInstance(Config.serverUrl, Config.appId, Config.merchant_private_key, Config.version,
        //                Config.sign_type, Config.alipay_public_key, Config.charset);

        //private LogHelper log = new LogHelper(AppDomain.CurrentDomain.BaseDirectory + "/log/log.txt");

        [WebMethod(Description = "支付宝扫码支付获取二维码参数。cardID:用户参数(卡号); money:充值金额(元); order_No:订单编号")]
        public string getQr_code(string cardID, string money, string OutTradeNo)
        {
            AlipayOrderInfo ai = new AlipayOrderInfo();
            string code_url = "";

            //=========================================
            AlipayTradePrecreateContentBuilder builder = ai.BuildPrecreateContent(money, OutTradeNo);
            ai.log.WriteLine("builder：" + builder.body+","+ builder.operator_id+","+ builder.out_trade_no+","+ builder.discountable_amount+","+ builder.total_amount);
            string out_trade_no = builder.out_trade_no;

            //如果需要接收扫码支付异步通知，那么请把下面两行注释代替本行。
            //推荐使用轮询撤销机制，不推荐使用异步通知,避免单边账问题发生。
             AlipayF2FPrecreateResult precreateResult = ai.serviceClient.tradePrecreate(builder);
           // string notify_url = "http://119.23.66.136/notify_url.aspx";  //商户接收异步通知的地址
           // AlipayF2FPrecreateResult precreateResult = ai.serviceClient.tradePrecreate(builder, notify_url);

            //以下返回结果的处理供参考。
            //payResponse.QrCode即二维码对于的链接
            //将链接用二维码工具生成二维码打印出来，顾客可以用支付宝钱包扫码支付。
            string result = "null...";
            ai.log.WriteLine("precreateResult.Status：" + precreateResult.Status);
            try
            {
                switch (precreateResult.Status)
                {
                    case ResultEnum.SUCCESS:
                        //获取二维码字符串
                        result = "支付请求生成成功，等待用户扫码支付";
                        code_url = precreateResult.response.QrCode;

                        //轮询订单结果
                        //根据业务需要，选择是否新起线程进行轮询
                        ParameterizedThreadStart ParStart = new ParameterizedThreadStart(ai.LoopQuery);
                        Thread myThread = new Thread(ParStart);
                        //object o = precreateResult.response.OutTradeNo;
                        object o = new MyOrderInfo() { order_no = precreateResult.response.OutTradeNo, userId = cardID };
                        myThread.Start(o);
                        break;
                    case ResultEnum.FAILED:
                        result = precreateResult.response.Body;
                        break;

                    case ResultEnum.UNKNOWN:
                        if (precreateResult.response == null)
                        {
                            result = "配置或网络异常，请检查后重试";
                        }
                        else
                        {
                            result = "系统异常，请更新外部订单后重新发起请求";
                        }
                        break;
                }
                ai.log.WriteLine("预支付订单生成结果：" + result);
            }
#pragma warning disable CS0168 // 声明了变量“ex”，但从未使用过
            catch (Exception ex)
#pragma warning restore CS0168 // 声明了变量“ex”，但从未使用过
            {
                return code_url;
            }
            return code_url;
        }

      
    }

}
